package com.test.controller.superadmin;

import com.test.bean.Area;
import com.test.bean.BaseConnectionInfo;
import com.test.service.IAreaService;
import com.test.util.datasource.DBIdentifier;
import com.test.util.datasource.ProjectDBMgr;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Description: 区域控制器
 * @Author: xiangty
 * @Date: 2018-11-11
 *
 * RestController 等效于 Controller和RequestBody两个注解
 */
@RestController
@RequestMapping("/superadmin")
@SuppressWarnings("all")
public class AreaController {

    private static Logger logger = LoggerFactory.getLogger(AreaController.class);

    @Autowired
    private IAreaService areaService;
    @Autowired
    SqlSessionFactoryBean sqlSessionFactory;

    @RequestMapping(value = "/listarea", method = RequestMethod.GET)
    private Map<String, Object> listArea(){
        logger.info("查询所有地区开始");
        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<Area> list = new ArrayList<>();

        try{
            //测试对mapper.xml的解析
           // XMLMapperBuilder builder = new XMLMapperBuilder();
           /* DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document doc = documentBuilder.parse("D:\\aa_bulesky\\project\\project02\\ssm\\springmvcspringmybatis\\src\\main\\resources\\mapper\\AreaMapper.xml");
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xPath = xPathFactory.newXPath();
            XPathExpression compile = xPath.compile("//book/title/text()");
            Object result = compile.evaluate(doc, XPathConstants.NODESET);
            NodeList nodeList = (NodeList) result;


            FileSystemResource systemResource= new FileSystemResource("D:\\aa_bulesky\\project\\project02\\ssm\\springmvcspringmybatis\\src\\main\\resources\\mapper\\AreaMapper.xml");
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(systemResource.getInputStream(), new Configuration(), systemResource.toString(), new Configuration().getSqlFragments());


*/
//            FileSystemResource systemResource= new FileSystemResource("D:\\aa_bulesky\\project\\project02\\ssm\\springmvcspringmybatis\\src\\main\\resources\\mapper\\AreaMapper.xml");
//            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(systemResource.getInputStream(), new Configuration(), systemResource.toString(), new Configuration().getSqlFragments());
//            XNode xNode = xmlMapperBuilder..evalNode("/mapper");
            String resouce2 = "D:\\aa_bulesky\\project\\project02\\ssm\\springmvcspringmybatis\\src\\main\\resources\\mapper\\AreaMapper02.xml";
            String space = "space02";
            String queryId = "queryArea02";
            Map map = new HashMap();
            map.put("name", "china");
            map.put("desc", 1);
            SqlSession session = null;
            try {
                SqlSessionFactory sessionFactory = sqlSessionFactory.getObject();
                session = sessionFactory.openSession();
                Configuration config = session.getConfiguration();

                InputStream inputStream = new FileSystemResource(resouce2).getInputStream();//Resources.getResourceAsStream(resouce2);通過該方式可能找不到新增的文件
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, config, resouce2, config.getSqlFragments());
                Collection<String> a = config.getMappedStatementNames();
                if (!a.contains(space + "." + queryId)) {
                    mapperParser.parse();
                }
                BoundSql boundSql = config.getMappedStatement(queryId).getBoundSql(map);
                Object area = session.selectOne(queryId, map);
            }catch (Exception e) {
                logger.info("文件：" +  resouce2 + "查询出错",e );
            }finally {
                if(null != session) {
                    session.close();
                }
            }
            map.put("name", "China_test02");
            String schemaCode = "111ffff";
            DBIdentifier.setProjectCode(schemaCode);//后面设置为数据表那条信息的id
            BaseConnectionInfo info = new BaseConnectionInfo();
            info.setDriver("com.mysql.jdbc.Driver");
            info.setUrl("jdbc:mysql://localhost:3306/datasource_test?useUnicode=true&characterEncoding=utf8");
            info.setName("root");
            info.setPassword("root");
            //ProjectDBMgr.getInstance(schemaCode, info);

            list = areaService.getAreaList(map);
            modelMap.put("rows",list);
            modelMap.put("total",list.size());
        } catch (Exception e){
            e.printStackTrace();
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
        }
        logger.info("查询所有地区结束");
        return modelMap;
    }

}
